<template>
  <div class="p-2">
    <!-- 聚合计算 - 聚合指标列表页面 -->
    <!-- 查询表单 -->
    <el-card shadow="hover" style="margin-bottom: 8px">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="100px">
        <el-form-item label="指标名称" prop="indicatorName">
          <el-input v-model="queryParams.indicatorName" placeholder="请输入指标名称" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="指标类型" prop="indicatorType">
          <el-select v-model="queryParams.indicatorType" placeholder="请选择指标类型" clearable style="width: 150px">
            <el-option label="全部" value="" />
            <el-option label="求和" value="sum" />
            <el-option label="平均值" value="avg" />
            <el-option label="最大值" value="max" />
            <el-option label="最小值" value="min" />
            <el-option label="计数" value="count" />
            <el-option label="标准差" value="stddev" />
          </el-select>
        </el-form-item>
        <el-form-item label="数据源" prop="dataSource">
          <el-input v-model="queryParams.dataSource" placeholder="请输入数据源" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="全部" value="" />
            <el-option label="启用" value="enabled" />
            <el-option label="禁用" value="disabled" />
            <el-option label="运行中" value="running" />
            <el-option label="已停止" value="stopped" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="20" style="margin-bottom: 8px">
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-item">
            <div class="stat-icon" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%)">
              <el-icon size="24"><TrendCharts /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ statistics.totalIndicators }}</div>
              <div class="stat-label">总指标数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-item">
            <div class="stat-icon" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%)">
              <el-icon size="24"><VideoPlay /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ statistics.runningIndicators }}</div>
              <div class="stat-label">运行中</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-item">
            <div class="stat-icon" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)">
              <el-icon size="24"><DataBoard /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ statistics.todayCalculations }}</div>
              <div class="stat-label">今日计算</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-item">
            <div class="stat-icon" style="background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)">
              <el-icon size="24"><Warning /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ statistics.errorIndicators }}</div>
              <div class="stat-label">异常指标</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 操作按钮 -->
    <el-card shadow="hover" style="margin-bottom: 8px">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleAdd">新建指标</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" plain icon="Edit" @click="handleBatchEdit" :disabled="!multiple">批量编辑</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="VideoPlay" @click="handleBatchStart" :disabled="!multiple">批量启动</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="info" plain icon="VideoPause" @click="handleBatchStop" :disabled="!multiple">批量停止</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="Delete" @click="handleBatchDelete" :disabled="!multiple">批量删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Download" @click="handleExport">导出配置</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" plain icon="Upload" @click="handleImport">导入配置</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="hover">
      <el-table v-loading="loading" :data="indicatorList" border stripe @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="序号" type="index" width="60" align="center" />
        <el-table-column label="指标名称" prop="indicatorName" width="200" show-overflow-tooltip>
          <template #default="scope">
            <el-link type="primary" @click="viewDetail(scope.row)">{{ scope.row.indicatorName }}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="指标类型" prop="indicatorType" width="120" align="center">
          <template #default="scope">
            <el-tag :type="getIndicatorTypeTag(scope.row.indicatorType)" size="small">{{ getIndicatorTypeText(scope.row.indicatorType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="数据源" prop="dataSource" width="180" show-overflow-tooltip />
        <el-table-column label="聚合字段" prop="aggregateField" width="150" show-overflow-tooltip />
        <el-table-column label="时间窗口" prop="timeWindow" width="120" align="center">
          <template #default="scope">
            <span>{{ scope.row.timeWindow }}{{ scope.row.timeUnit }}</span>
          </template>
        </el-table-column>
        <el-table-column label="计算频率" prop="frequency" width="120" align="center">
          <template #default="scope">
            <span>{{ scope.row.frequency }}{{ scope.row.frequencyUnit }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getStatusTag(scope.row.status)" size="small">{{ getStatusText(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="最新值" prop="latestValue" width="120" align="center">
          <template #default="scope">
            <span class="latest-value" :class="getValueClass(scope.row.trend)">{{ scope.row.latestValue }}</span>
            <el-icon v-if="scope.row.trend === 'up'" class="trend-icon up"><CaretTop /></el-icon>
            <el-icon v-if="scope.row.trend === 'down'" class="trend-icon down"><CaretBottom /></el-icon>
          </template>
        </el-table-column>
        <el-table-column label="更新时间" prop="updateTime" width="160" show-overflow-tooltip />
        <el-table-column label="创建时间" prop="createTime" width="160" show-overflow-tooltip />
        <el-table-column label="操作" align="center" width="280" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="查看详情" placement="top">
              <el-button link type="primary" icon="View" @click="viewDetail(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="编辑" placement="top">
              <el-button link type="success" icon="Edit" @click="handleEdit(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="查看数据" placement="top">
              <el-button link type="warning" icon="DataBoard" @click="viewData(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="启动/停止" placement="top">
              <el-button link :type="scope.row.status === 'running' ? 'info' : 'success'" 
                :icon="scope.row.status === 'running' ? 'VideoPause' : 'VideoPlay'" 
                @click="toggleStatus(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="复制" placement="top">
              <el-button link type="warning" icon="CopyDocument" @click="copyIndicator(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 指标详情对话框 -->
    <el-dialog title="指标详情" v-model="detailDialog.visible" width="900px" append-to-body>
      <div v-if="detailDialog.data">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="指标名称">{{ detailDialog.data.indicatorName }}</el-descriptions-item>
          <el-descriptions-item label="指标描述">{{ detailDialog.data.description }}</el-descriptions-item>
          <el-descriptions-item label="指标类型">
            <el-tag :type="getIndicatorTypeTag(detailDialog.data.indicatorType)" size="small">{{ getIndicatorTypeText(detailDialog.data.indicatorType) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="数据源">{{ detailDialog.data.dataSource }}</el-descriptions-item>
          <el-descriptions-item label="聚合字段">{{ detailDialog.data.aggregateField }}</el-descriptions-item>
          <el-descriptions-item label="过滤条件">{{ detailDialog.data.filterCondition || '无' }}</el-descriptions-item>
          <el-descriptions-item label="时间窗口">{{ detailDialog.data.timeWindow }}{{ detailDialog.data.timeUnit }}</el-descriptions-item>
          <el-descriptions-item label="计算频率">{{ detailDialog.data.frequency }}{{ detailDialog.data.frequencyUnit }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTag(detailDialog.data.status)" size="small">{{ getStatusText(detailDialog.data.status) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="最新值">{{ detailDialog.data.latestValue }}</el-descriptions-item>
          <el-descriptions-item label="创建人">{{ detailDialog.data.createBy }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ detailDialog.data.createTime }}</el-descriptions-item>
          <el-descriptions-item label="计算公式" :span="2">
            <div class="formula-display">
              <pre>{{ detailDialog.data.formula }}</pre>
            </div>
          </el-descriptions-item>
        </el-descriptions>
        
        <!-- 历史数据图表 -->
        <el-divider>历史数据趋势</el-divider>
        <div class="chart-container" ref="historyChart"></div>
      </div>
    </el-dialog>

    <!-- 数据查看对话框 -->
    <el-dialog title="指标数据" v-model="dataDialog.visible" width="1000px" append-to-body>
      <div class="data-view-container">
        <el-row :gutter="20" style="margin-bottom: 20px">
          <el-col :span="8">
            <el-date-picker
              v-model="dataQuery.dateRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            />
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="queryData">查询数据</el-button>
          </el-col>
        </el-row>
        
        <el-tabs v-model="dataViewTab">
          <el-tab-pane label="图表视图" name="chart">
            <div class="chart-container" ref="dataChart"></div>
          </el-tab-pane>
          <el-tab-pane label="表格视图" name="table">
            <el-table :data="dataList" border stripe max-height="400">
              <el-table-column label="时间" prop="timestamp" width="180" />
              <el-table-column label="值" prop="value" width="120" align="center" />
              <el-table-column label="单位" prop="unit" width="80" align="center" />
              <el-table-column label="状态" prop="status" width="100" align="center">
                <template #default="scope">
                  <el-tag :type="scope.row.status === 'normal' ? 'success' : 'warning'" size="small">
                    {{ scope.row.status === 'normal' ? '正常' : '异常' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="备注" prop="remark" show-overflow-tooltip />
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>

    <!-- 新建/编辑指标对话框 -->
    <el-dialog :title="form.id ? '编辑指标' : '新建指标'" v-model="formDialog.visible" width="800px" append-to-body>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="指标名称" prop="indicatorName">
              <el-input v-model="form.indicatorName" placeholder="请输入指标名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="指标类型" prop="indicatorType">
              <el-select v-model="form.indicatorType" placeholder="请选择指标类型" style="width: 100%">
                <el-option label="求和" value="sum" />
                <el-option label="平均值" value="avg" />
                <el-option label="最大值" value="max" />
                <el-option label="最小值" value="min" />
                <el-option label="计数" value="count" />
                <el-option label="标准差" value="stddev" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="数据源" prop="dataSource">
              <el-input v-model="form.dataSource" placeholder="请输入数据源" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="聚合字段" prop="aggregateField">
              <el-input v-model="form.aggregateField" placeholder="请输入聚合字段" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="时间窗口" prop="timeWindow">
              <el-input-number v-model="form.timeWindow" :min="1" placeholder="时间窗口" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="时间单位" prop="timeUnit">
              <el-select v-model="form.timeUnit" style="width: 100%">
                <el-option label="秒" value="s" />
                <el-option label="分" value="m" />
                <el-option label="时" value="h" />
                <el-option label="天" value="d" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="计算频率" prop="frequency">
              <el-input-number v-model="form.frequency" :min="1" placeholder="计算频率" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="频率单位" prop="frequencyUnit">
              <el-select v-model="form.frequencyUnit" style="width: 100%">
                <el-option label="秒" value="s" />
                <el-option label="分" value="m" />
                <el-option label="时" value="h" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="过滤条件" prop="filterCondition">
          <el-input v-model="form.filterCondition" type="textarea" :rows="3" placeholder="请输入过滤条件（SQL WHERE子句）" />
        </el-form-item>
        <el-form-item label="计算公式" prop="formula">
          <el-input v-model="form.formula" type="textarea" :rows="4" placeholder="请输入计算公式" />
        </el-form-item>
        <el-form-item label="指标描述" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入指标描述" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="enabled">启用</el-radio>
            <el-radio label="disabled">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="formDialog.visible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="IndicatorList" lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete, VideoPlay, VideoPause, Download, Upload, View, DataBoard, CopyDocument } from '@element-plus/icons-vue'
import { TrendCharts, Warning, CaretTop, CaretBottom } from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const total = ref(0)
const indicatorList = ref([])
const multiple = ref(false)
const ids = ref([])
const dataViewTab = ref('chart')

// 统计数据
const statistics = reactive({
  totalIndicators: '156',
  runningIndicators: '89',
  todayCalculations: '12,456',
  errorIndicators: '3'
})

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  indicatorName: '',
  indicatorType: '',
  dataSource: '',
  status: ''
})

// 数据查询参数
const dataQuery = reactive({
  dateRange: []
})

// 数据列表
const dataList = ref([])

// 对话框
const detailDialog = reactive({
  visible: false,
  data: null
})

const dataDialog = reactive({
  visible: false,
  data: null
})

const formDialog = reactive({
  visible: false
})

// 表单数据
const form = reactive({
  id: null,
  indicatorName: '',
  indicatorType: '',
  dataSource: '',
  aggregateField: '',
  timeWindow: 1,
  timeUnit: 'h',
  frequency: 1,
  frequencyUnit: 'm',
  filterCondition: '',
  formula: '',
  description: '',
  status: 'enabled'
})

// 表单验证规则
const rules = {
  indicatorName: [{ required: true, message: '请输入指标名称', trigger: 'blur' }],
  indicatorType: [{ required: true, message: '请选择指标类型', trigger: 'change' }],
  dataSource: [{ required: true, message: '请输入数据源', trigger: 'blur' }],
  aggregateField: [{ required: true, message: '请输入聚合字段', trigger: 'blur' }],
  timeWindow: [{ required: true, message: '请输入时间窗口', trigger: 'blur' }],
  frequency: [{ required: true, message: '请输入计算频率', trigger: 'blur' }]
}

// 获取指标类型标签样式
const getIndicatorTypeTag = (type: string) => {
  switch (type) {
    case 'sum': return 'primary'
    case 'avg': return 'success'
    case 'max': return 'danger'
    case 'min': return 'warning'
    case 'count': return 'info'
    case 'stddev': return ''
    default: return 'info'
  }
}

// 获取指标类型文本
const getIndicatorTypeText = (type: string) => {
  switch (type) {
    case 'sum': return '求和'
    case 'avg': return '平均值'
    case 'max': return '最大值'
    case 'min': return '最小值'
    case 'count': return '计数'
    case 'stddev': return '标准差'
    default: return '未知'
  }
}

// 获取状态标签样式
const getStatusTag = (status: string) => {
  switch (status) {
    case 'enabled': return 'success'
    case 'disabled': return 'info'
    case 'running': return 'primary'
    case 'stopped': return 'warning'
    default: return 'info'
  }
}

// 获取状态文本
const getStatusText = (status: string) => {
  switch (status) {
    case 'enabled': return '启用'
    case 'disabled': return '禁用'
    case 'running': return '运行中'
    case 'stopped': return '已停止'
    default: return '未知'
  }
}

// 获取数值样式类
const getValueClass = (trend: string) => {
  return trend === 'up' ? 'value-up' : trend === 'down' ? 'value-down' : ''
}

// 查询指标列表
const getList = () => {
  loading.value = true
  // 模拟数据
  setTimeout(() => {
    indicatorList.value = [
      {
        id: 'IND001',
        indicatorName: '设备平均温度',
        indicatorType: 'avg',
        dataSource: 'sensor_data',
        aggregateField: 'temperature',
        timeWindow: 1,
        timeUnit: 'h',
        frequency: 5,
        frequencyUnit: 'm',
        filterCondition: 'device_type = "temperature_sensor"',
        formula: 'AVG(temperature)',
        description: '计算所有温度传感器在1小时内的平均温度值',
        status: 'running',
        latestValue: '25.6°C',
        trend: 'up',
        updateTime: '2024-01-15 14:30:25',
        createTime: '2024-01-10 09:15:30',
        createBy: 'admin'
      },
      {
        id: 'IND002',
        indicatorName: '设备在线数量',
        indicatorType: 'count',
        dataSource: 'device_status',
        aggregateField: 'device_id',
        timeWindow: 30,
        timeUnit: 'm',
        frequency: 1,
        frequencyUnit: 'm',
        filterCondition: 'status = "online"',
        formula: 'COUNT(DISTINCT device_id)',
        description: '统计30分钟内在线设备的数量',
        status: 'running',
        latestValue: '1,256',
        trend: 'stable',
        updateTime: '2024-01-15 14:29:15',
        createTime: '2024-01-10 10:20:45',
        createBy: 'admin'
      },
      {
        id: 'IND003',
        indicatorName: '每日数据总量',
        indicatorType: 'sum',
        dataSource: 'message_log',
        aggregateField: 'data_size',
        timeWindow: 1,
        timeUnit: 'd',
        frequency: 1,
        frequencyUnit: 'h',
        filterCondition: '',
        formula: 'SUM(data_size)',
        description: '计算每日接收的数据总量',
        status: 'running',
        latestValue: '125.6GB',
        trend: 'up',
        updateTime: '2024-01-15 14:00:00',
        createTime: '2024-01-08 16:30:20',
        createBy: 'operator'
      },
      {
        id: 'IND004',
        indicatorName: '最高CPU使用率',
        indicatorType: 'max',
        dataSource: 'system_metrics',
        aggregateField: 'cpu_usage',
        timeWindow: 15,
        timeUnit: 'm',
        frequency: 1,
        frequencyUnit: 'm',
        filterCondition: 'metric_type = "cpu"',
        formula: 'MAX(cpu_usage)',
        description: '监控15分钟内系统的最高CPU使用率',
        status: 'enabled',
        latestValue: '78.5%',
        trend: 'down',
        updateTime: '2024-01-15 14:28:30',
        createTime: '2024-01-12 11:45:15',
        createBy: 'admin'
      },
      {
        id: 'IND005',
        indicatorName: '告警事件计数',
        indicatorType: 'count',
        dataSource: 'alarm_events',
        aggregateField: 'event_id',
        timeWindow: 1,
        timeUnit: 'h',
        frequency: 10,
        frequencyUnit: 'm',
        filterCondition: 'severity >= "warning"',
        formula: 'COUNT(event_id)',
        description: '统计1小时内警告级别以上的告警事件数量',
        status: 'stopped',
        latestValue: '12',
        trend: 'stable',
        updateTime: '2024-01-15 13:50:10',
        createTime: '2024-01-11 14:20:35',
        createBy: 'operator'
      }
    ]
    total.value = 156
    loading.value = false
  }, 1000)
}

// 搜索
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置
const resetQuery = () => {
  queryParams.indicatorName = ''
  queryParams.indicatorType = ''
  queryParams.dataSource = ''
  queryParams.status = ''
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection: any[]) => {
  ids.value = selection.map(item => item.id)
  multiple.value = !selection.length
}

// 新增指标
const handleAdd = () => {
  resetForm()
  formDialog.visible = true
}

// 编辑指标
const handleEdit = (row: any) => {
  resetForm()
  Object.assign(form, row)
  formDialog.visible = true
}

// 查看详情
const viewDetail = (row: any) => {
  detailDialog.data = row
  detailDialog.visible = true
  // 这里可以初始化历史数据图表
  nextTick(() => {
    // 初始化图表的代码
  })
}

// 查看数据
const viewData = (row: any) => {
  dataDialog.data = row
  dataDialog.visible = true
  // 模拟数据
  dataList.value = [
    { timestamp: '2024-01-15 14:30:00', value: '25.6', unit: '°C', status: 'normal', remark: '' },
    { timestamp: '2024-01-15 14:25:00', value: '25.4', unit: '°C', status: 'normal', remark: '' },
    { timestamp: '2024-01-15 14:20:00', value: '25.8', unit: '°C', status: 'normal', remark: '' },
    { timestamp: '2024-01-15 14:15:00', value: '26.1', unit: '°C', status: 'abnormal', remark: '温度偏高' },
    { timestamp: '2024-01-15 14:10:00', value: '25.3', unit: '°C', status: 'normal', remark: '' }
  ]
}

// 切换状态
const toggleStatus = (row: any) => {
  const action = row.status === 'running' ? '停止' : '启动'
  ElMessageBox.confirm(`确认${action}指标 "${row.indicatorName}"？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    row.status = row.status === 'running' ? 'stopped' : 'running'
    ElMessage.success(`${action}成功`)
  })
}

// 复制指标
const copyIndicator = (row: any) => {
  ElMessage.success('指标复制成功，请修改指标名称')
  resetForm()
  Object.assign(form, { ...row, id: null, indicatorName: row.indicatorName + '_copy' })
  formDialog.visible = true
}

// 删除指标
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确认删除指标 "' + row.indicatorName + '"？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
    getList()
  })
}

// 批量编辑
const handleBatchEdit = () => {
  ElMessage.info('批量编辑功能开发中')
}

// 批量启动
const handleBatchStart = () => {
  ElMessageBox.confirm(`确认启动选中的 ${ids.value.length} 个指标？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('批量启动成功')
    getList()
  })
}

// 批量停止
const handleBatchStop = () => {
  ElMessageBox.confirm(`确认停止选中的 ${ids.value.length} 个指标？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('批量停止成功')
    getList()
  })
}

// 批量删除
const handleBatchDelete = () => {
  ElMessageBox.confirm(`确认删除选中的 ${ids.value.length} 个指标？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('批量删除成功')
    getList()
  })
}

// 导出配置
const handleExport = () => {
  ElMessage.success('配置导出中，请稍候...')
}

// 导入配置
const handleImport = () => {
  ElMessage.info('配置导入功能开发中')
}

// 查询数据
const queryData = () => {
  ElMessage.success('数据查询成功')
}

// 重置表单
const resetForm = () => {
  form.id = null
  form.indicatorName = ''
  form.indicatorType = ''
  form.dataSource = ''
  form.aggregateField = ''
  form.timeWindow = 1
  form.timeUnit = 'h'
  form.frequency = 1
  form.frequencyUnit = 'm'
  form.filterCondition = ''
  form.formula = ''
  form.description = ''
  form.status = 'enabled'
}

// 提交表单
const submitForm = () => {
  // 这里添加表单验证和提交逻辑
  ElMessage.success(form.id ? '编辑成功' : '新增成功')
  formDialog.visible = false
  getList()
}

// 组件挂载
onMounted(() => {
  getList()
})
</script>

<style scoped>
.mb8 {
  margin-bottom: 8px;
}

.stat-card {
  cursor: pointer;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.stat-item {
  display: flex;
  align-items: center;
  padding: 10px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  margin-right: 15px;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.latest-value {
  font-weight: bold;
  display: inline-flex;
  align-items: center;
}

.value-up {
  color: #67c23a;
}

.value-down {
  color: #f56c6c;
}

.trend-icon {
  margin-left: 4px;
  font-size: 12px;
}

.trend-icon.up {
  color: #67c23a;
}

.trend-icon.down {
  color: #f56c6c;
}

.formula-display {
  background: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 15px;
  max-height: 200px;
  overflow-y: auto;
}

.formula-display pre {
  margin: 0;
  font-family: 'Courier New', monospace;
  font-size: 13px;
  line-height: 1.5;
  color: #303133;
}

.chart-container {
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  background: #f5f7fa;
  border-radius: 4px;
  margin-top: 15px;
}

.data-view-container {
  min-height: 400px;
}
</style>